package com.ruoyi.miniapp.util;

import org.apache.commons.collections4.map.LRUMap;
/**
 * 幂等性判断
 * @ClassName
 * @Description
 * @Date 2022/4/9 11:24
 * @Author songping
 */
public class IdempotentUtils {

    private static LRUMap<String, Long> reqCache = new LRUMap<>(100);

    private static Long WAIT_TIME = 10L;//秒
    /**
     * 幂等性判断
     * @return
     */
    public static boolean judge (String id,Object lockClass) {
        synchronized (lockClass) {
            reqCache.entrySet().parallelStream().forEach((entry) ->{
                System.out.println("防重复提交key---"+entry.getKey());
                System.out.println("防重复提交value---"+entry.getValue());
            });
            // 重复请求判断
            if (reqCache.containsKey(id)) {
                // 重复请求
                long currentTimeMillis = System.currentTimeMillis();
                Long lastTimeMillis = reqCache.get(id);
                if(currentTimeMillis< (lastTimeMillis+(WAIT_TIME*1000))){
                    System.out.println("请勿重复提交！！！" + id);
                    return false;
                }
                else
                {
                    reqCache.put(id,currentTimeMillis);
                    return true;
                }
            }
            // 非重复请求，存储请求 ID
            reqCache.put(id, System.currentTimeMillis());
        }
        return true;
    }

    /**
     * 删除key
     * @param id
     * @return
     */
    public static void remove(String id){
        if(reqCache.containsKey(id)){
            reqCache.remove(id);
        }
    }
}
